import { ObjectLiteral, SelectQueryBuilder } from 'typeorm';

export function querySimplify<T extends ObjectLiteral>(
  sqlPromise: SelectQueryBuilder<T>,
  findOptions: {
    [key: string]:
      | {
          value: NonNullable<any>;
          operate: string;
        }
      | string
      | number
      | undefined;
  },
  hasWhere = false,
) {
  if (!hasWhere) {
    sqlPromise = sqlPromise.where('');
  }
  for (const [field, option] of Object.entries(findOptions)) {
    if (option) {
      if (typeof option === 'object') {
        sqlPromise = sqlPromise.andWhere(`${field} ${option.operate} :value`, {
          value: option.value,
        });
      } else {
        sqlPromise = sqlPromise.andWhere(`${field} = :value`, {
          value: option,
        });
      }
    }
  }
  return sqlPromise;
}
